﻿using Microsoft.AspNet.SignalR.Client;
using System;
using System.Windows;
using ZSoft.PushServices.Net.DTO;

namespace WpfClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        const string HOST = "http://localhost:10765";
        private HubConnection _connection;
        private IHubProxy _proxy;
        string deviceId = Guid.NewGuid().ToString();

        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this._connection = new HubConnection(HOST);

            this._proxy = this._connection.CreateHubProxy("NotificationHub");

            _connection.StateChanged += _connection_StateChanged;

            this._proxy.On("Notify", (NotificationDTO notification) =>
            {
                Dispatcher.Invoke(() =>
                {
                    this.ListBox.Items.Add(notification.AppId + notification.Title + " >> " + notification.Message);
                });
            });

            try
            {
                await _connection.Start().ContinueWith(t =>
                {
                    _proxy.Invoke("Identified", new ClientInfoDTO()
                    {
                        AppId = 1223.ToString(),
                        DeviceId = deviceId + " --WPF"
                    });
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void _connection_StateChanged(StateChange obj)
        {
            this.Dispatcher.Invoke(() =>
            {
                this.ConnectinStatus.Content = obj.NewState;
            });
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
        }
    }
}